package logic

import (
	"context"
	"time"
	"strings"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/helper"


	"github.com/zeromicro/go-zero/core/logx"
	"github.com/eeppee_admin/clouddisk/service/model"

)

type EmailCodeSendLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewEmailCodeSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailCodeSendLogic {
	return &EmailCodeSendLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// http POST :8888/email/code/send/register email=1690544550@qq.com
func (l *EmailCodeSendLogic) EmailCodeSend(req *types.EmailCodeSendRequest) (resp *types.EmailCodeSendResponse, err error) {
	resp = &types.EmailCodeSendResponse{} // 初始化 resp
	l.Logger.Info("Received request", logx.Field("email", req.Email))

	// 验证邮箱是否为空
	if req.Email == "" {
		resp.Msg = "邮箱不能为空"
		return resp, nil
	}

	// 验证邮箱格式
	if !strings.Contains(req.Email, "@") {
		resp.Msg = "邮箱格式不正确"
		return resp, nil
	}

	// 该邮箱未被注册
	cnt, err := l.svcCtx.Engine.Where("email = ?", req.Email).Count(new(model.User))
	if err != nil {
		resp.Msg = "发送邮箱验证码失败"
		l.Logger.Error("Failed to check email", logx.Field("error", err))
		return resp, nil
	}

	if cnt > 0 {
		resp.Msg = "该邮箱已经注册，请使用其他邮箱"
		return resp, nil
	}

	// 获取验证码
	code := helper.RandCode()
	// 存储验证码到Redis
	_, err = l.svcCtx.RDB.Set(l.ctx, req.Email, code, time.Second * time.Duration(l.svcCtx.Config.Email.CodeExpired)).Result()
	if err != nil {
		resp.Msg = "发送邮箱验证码失败"
		l.Logger.Error("Failed to set code in Redis", logx.Field("error", err))
		return resp, nil
	}

	// 发送验证码
	err = helper.SendEmail(req.Email, code)
	if err != nil {
		resp.Msg = "发送邮箱验证码失败" + err.Error()
		l.Logger.Error("Failed to send email", logx.Field("error", err))
		return resp, nil
	}

	resp.Msg = "发送邮箱验证码成功"
	return resp, nil
}